package com.pan.insist.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pan.insist.dao.UserMapper;
import com.pan.insist.model.UserModel;
import com.pan.insist.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Set;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author kaiji
 * @since 2019-08-17
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserModel> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public UserModel getUserByExist(String id, String phone) {
        return userMapper.getUserByExist(id, phone);
    }

    @Override
    public Set<String> getRoleByPhone(String phone) {
        return userMapper.getRoleByPhone(phone);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public boolean updateByUserInfo(UserModel userModel) {
        try {
            // 1. 删除这个用户先关的角色
            userMapper.deleteRoleByUserId(userModel.getId());
            // 2. 保存这个用户与当前选择的角色关系
            for (String roleId : userModel.getRoleIds()) {
                userMapper.saveUserAndRole(userModel.getId(), roleId);
            }
            // 3. 编辑的用户信息
            userMapper.updateById(userModel);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public void saveAndRole(UserModel userModel) {
        userMapper.insert(userModel);
        for (String roleId : userModel.getRoleIds()) {
            userMapper.saveUserAndRole(userModel.getId(), roleId);
        }
    }
}
